#!/usr/bin/env python
# -*- coding: UTF8 -*-

""" docstring """

__author__      = "Hao FengGe (xxhfg@163.com)"
__version__     = "@Revision: 0.1 $"
__date__        = "@Update  : 2011/03/17 18:01:27 $"
__copyright__   = "Copyright (c) 2010 Hao FengGe"
__license__     = "Python"

import httplib2
import re
import sqlite3
import time
from common import * 
from rules_qxc import * 

class HTTP_TRANS_ERROR(Exception):
    pass
class PARSER_DATA_ERROR(Exception):
    pass
class INSERT_DATA_ERROR(Exception):
    pass
class QUERY_DATA_ERROR(Exception):
    pass
class DATA_FORMAT_ERROR(Exception):
    pass

def get_qxc(url):
    """下载七星彩数据"""
    # url = 'http://www.lottery.gov.cn/lottery/qxc/History.aspx'

    try:
        h = httplib2.Http('.cache')
        response, content = h.request(url)
        if response.status == 200:
            return (response.status, content)
        else:
            raise HTTP_TRANS_ERROR
    except Exception:
        raise HTTP_TRANS_ERROR

def parser_qxc(content):
    """分解HTML文件得到七星彩数据 for parser_qxc"""

    pattern1 = r'<TD height="24">\r\n\s*?(\d{5})\s*?\r\n\s*?</TD>'
    m_qishu = re.findall(pattern1, content)

    pattern2 = r'(\d&nbsp;&nbsp;\d&nbsp;&nbsp;\d&nbsp;&nbsp;\d&nbsp;&nbsp;\d&nbsp;&nbsp;\d&nbsp;&nbsp;\d)'
    m_number = re.findall(pattern2, content)
    m_num = [re.split(r'&nbsp;&nbsp;', number) for number in m_number]

    pattern3 = r'<TD>\r\n\s*?(\d{4}-\d{2}-\d{2})\s*?\r\n\s*?</TD>'
    m_riqi = re.findall(pattern3, content)

    if not len(m_qishu)==len(m_num)==len(m_riqi):
        raise PARSER_DATA_ERROR('解析历史数据失败！')
    else:
        result = []
        for i in range(len(m_qishu)):
            result.append([m_qishu[i], m_num[i], m_riqi[i]])
        return result

def add_data_to_db(data):
    """保存数据至数据库 for add_data_to_db"""
    if (not isinstance(data, (list, list))) or (len(data)==0):
        raise DATA_FORMAT_ERROR('数据格式错误！')

    # print data
    try:
        db = sqlite3.connect('caipiao.db')
        cursor = db.cursor()

        for dat in data:
            if not isinstance(dat, (list, list)):
                raise DATA_FORMAT_ERROR('数据格式错误！')

            try:
                qishu, haoma, riqi = dat
            except:
                raise DATA_FORMAT_ERROR('数据格式错误！')

            if re.search('\d{5}', qishu)==None:
                raise DATA_FORMAT_ERROR('qishu 数据格式错误！')
            if not (isinstance(haoma, (list, list)) and len(haoma)==7):
                raise DATA_FORMAT_ERROR('haoma 数据格式错误！')
            if re.search('\d{4}-\d{2}-\d{2}', riqi)==None:
                raise DATA_FORMAT_ERROR('riqi 数据格式错误！')

            msg = "正在处理第 %s 期 %s" % (qishu, haoma)
            Out_Msg(msg)
            cursor.execute('insert into lottery_qxc values(?, ?, ?, ?, ?, ?, ?, ?, ?)', \
                (qishu, haoma[0], haoma[1], haoma[2], haoma[3], haoma[4], \
                haoma[5], haoma[6], riqi))
            db.commit()
    except sqlite3.DatabaseError, exc:
        #error = exc.args
        #print "ErrorCode: " + str(error)
        error = "ErrorCode: " + str(exc.args)
        raise INSERT_DATA_ERROR(error)
    finally:
        db.close()

def get_data_from_db():
    """取出历史数据 for get_data_from_db"""
    try:
        db = sqlite3.connect('caipiao.db')
        cursor = db.cursor()
        cursor.execute('select * from lottery_qxc order by kaijiangriqi ')
        result = []
        for row in cursor:
            result.append(row)
    except sqlite3.DatabaseError, exc:
        error = "ErrorCode: " + str(exc.args)
        raise QUERY_DATA_ERROR(error)
    else:
        return result
    finally:
        db.close()


if __name__=='__main__':
    """
    url = 'http://www.lottery.gov.cn/lottery/qxc/History.aspx?p=%d'

    try:
        for i in range(1, 22):
            msg = "正在处理第 %02d 页" % i
            Out_Msg(msg)
            newurl = url % i
            status, content = get_qxc(newurl)
            data = parser_qxc(content)
            add_data_to_db(data)
    except:
        msg = '下载七星彩数据失败(Download Data Error)！'
        Out_Msg(msg)
    print 'end'
    """

    url = 'http://www.lottery.gov.cn/lottery/qxc/History.aspx'
    try:
        status, content = get_qxc(url)
        data = parser_qxc(content)
        add_data_to_db(data)
    except Exception, e:
        msg = e.message
        Out_Msg(msg)

    try:
        data = get_data_from_db()
    except:
        msg = '取出历史数据失败！'
        Out_Msg(msg)

    guess_lottery(data)
    print 'end'
